"""
AI对话框配置数据模型
"""

from datetime import datetime
from enum import Enum
from typing import List, Optional, Dict, Any

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class InteractiveMode:
    """交互模式枚举"""
    DIALOG = 1  # 对话框
    VOICE_CALL = 2  # 语音通话
    VIDEO_CHAT = 3  # 视频聊天

    @classmethod
    def get_mode_name(cls, value: int) -> str:
        """获取模式名称"""
        mode_names = {
            cls.DIALOG: "对话框",
            cls.VOICE_CALL: "语音通话",
            cls.VIDEO_CHAT: "视频聊天"
        }
        return mode_names.get(value, "未知模式")

    @classmethod
    def is_valid(cls, value: int) -> bool:
        """验证模式值是否有效"""
        return value in [cls.DIALOG, cls.VOICE_CALL, cls.VIDEO_CHAT]


class ButtonType(str, Enum):
    """按钮类型枚举"""
    PRIMARY = "primary"
    SECONDARY = "secondary"
    SUCCESS = "success"
    WARNING = "warning"
    DANGER = "danger"
    INFO = "info"
    TEXT = "text"


class DialogSize(BaseModel):
    """对话框尺寸配置"""
    width: int = Field(..., ge=200, le=2000, description="对话框宽度（像素）")
    height: int = Field(..., ge=150, le=1500, description="对话框高度（像素）")


class ButtonConfig(BaseModel):
    """按钮配置"""
    id: str = Field(..., min_length=1, max_length=50, description="按钮唯一标识")
    text: str = Field(..., min_length=1, max_length=100, description="按钮文本")
    type: ButtonType = Field(default=ButtonType.PRIMARY, description="按钮类型")
    icon: Optional[str] = Field(None, max_length=50, description="按钮图标")
    action: Optional[str] = Field(None, max_length=100, description="按钮动作")


class AIWebDialog(BaseModel):
    """AI对话框配置实体类"""
    id: int = Field(..., description="主键ID")
    scene_id: str = Field(..., max_length=50, description="场景ID")
    agent_ids: Optional[str] = Field(None, max_length=200, description="关联的Agent ID集合，多个ID用逗号分隔")
    dialog_size: DialogSize = Field(..., description="对话框尺寸配置")
    buttons: List[ButtonConfig] = Field(default_factory=list, description="按钮集合配置")
    interactive_mode: int = Field(..., ge=1, le=3, description="交互模式(1=对话框,2=语音通话,3=视频聊天)")
    transparency: int = Field(default=100, ge=0, le=100, description="对话框透明度（0-100）")
    created_time: datetime = Field(..., description="创建时间")
    updated_time: datetime = Field(..., description="更新时间")

    model_config = ConfigDict(from_attributes=True)

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_time' in data and data['created_time']:
            data['created_time'] = data['created_time'].isoformat()
        if 'updated_time' in data and data['updated_time']:
            data['updated_time'] = data['updated_time'].isoformat()
        return data

    @field_validator('buttons')
    @classmethod
    def validate_buttons_unique_ids(cls, v):
        """验证按钮ID唯一性"""
        if not v:
            return v

        button_ids = [button.id for button in v]
        if len(button_ids) != len(set(button_ids)):
            raise ValueError("按钮ID必须唯一")
        return v

    @field_validator('interactive_mode')
    @classmethod
    def validate_interactive_mode(cls, v):
        """验证交互模式"""
        if not InteractiveMode.is_valid(v):
            raise ValueError("交互模式必须是1(对话框)、2(语音通话)或3(视频聊天)")
        return v

    def get_mode_name(self) -> str:
        """获取交互模式名称"""
        return InteractiveMode.get_mode_name(self.interactive_mode)

    def get_button_by_id(self, button_id: str) -> Optional[ButtonConfig]:
        """根据ID获取按钮配置"""
        for button in self.buttons:
            if button.id == button_id:
                return button
        return None


class AIWebDialogCreate(BaseModel):
    """创建对话框配置请求模型"""
    scene_id: str = Field(..., max_length=50, description="场景ID")
    agent_ids: Optional[str] = Field(None, max_length=200, description="关联的Agent ID集合，多个ID用逗号分隔")
    dialog_size: DialogSize = Field(..., description="对话框尺寸配置")
    buttons: List[ButtonConfig] = Field(default_factory=list, description="按钮集合配置")
    interactive_mode: int = Field(..., ge=1, le=3, description="交互模式(1=对话框,2=语音通话,3=视频聊天)")
    transparency: int = Field(default=100, ge=0, le=100, description="对话框透明度（0-100）")

    @field_validator('buttons')
    @classmethod
    def validate_buttons_unique_ids(cls, v):
        """验证按钮ID唯一性"""
        if not v:
            return v

        button_ids = [button.id for button in v]
        if len(button_ids) != len(set(button_ids)):
            raise ValueError("按钮ID必须唯一")
        return v


class AIWebDialogUpdate(BaseModel):
    """更新对话框配置请求模型"""
    agent_ids: Optional[str] = Field(None, max_length=200, description="关联的Agent ID集合，多个ID用逗号分隔")
    dialog_size: Optional[DialogSize] = Field(None, description="对话框尺寸配置")
    buttons: Optional[List[ButtonConfig]] = Field(None, description="按钮集合配置")
    interactive_mode: Optional[int] = Field(None, ge=1, le=3, description="交互模式(1=对话框,2=语音通话,3=视频聊天)")
    transparency: Optional[int] = Field(None, ge=0, le=100, description="对话框透明度（0-100）")

    @field_validator('buttons')
    @classmethod
    def validate_buttons_unique_ids(cls, v):
        """验证按钮ID唯一性"""
        if not v:
            return v

        button_ids = [button.id for button in v]
        if len(button_ids) != len(set(button_ids)):
            raise ValueError("按钮ID必须唯一")
        return v


class AIWebDialogResponse(BaseModel):
    """对话框配置响应模型"""
    id: int
    scene_id: str
    agent_ids: Optional[str]
    dialog_size: DialogSize
    buttons: List[ButtonConfig]
    interactive_mode: int
    transparency: int
    created_time: datetime
    updated_time: datetime

    model_config = ConfigDict(from_attributes=True)


class AIWebDialogListResponse(BaseModel):
    """对话框配置列表响应模型"""
    total_count: int = Field(..., description="总数量")
    dialogs: List[AIWebDialogResponse] = Field(..., description="对话框配置列表")


class AIWebDialogQueryParams(BaseModel):
    """对话框配置查询参数"""
    scene_id: Optional[str] = Field(None, description="场景ID")
    interactive_mode: Optional[int] = Field(None, ge=1, le=3, description="交互模式")
    page: int = Field(default=1, ge=1, description="页码")
    page_size: int = Field(default=20, ge=1, le=100, description="每页数量")


class ButtonActionRequest(BaseModel):
    """按钮操作请求模型"""
    button_id: str = Field(..., description="按钮ID")
    action_type: str = Field(..., description="操作类型")
    action_data: Optional[Dict[str, Any]] = Field(None, description="操作数据")
